package filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import utils.JwtUtils;

//@WebFilter(urlPatterns = "/*") // 拦截所有请求
public abstract class LoginFilter implements Filter {

    // 白名单：无需登录的接口
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/login", "/register", "/static/"
    );
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("======== 过滤器初始化成功 ========");
        // 启动时查看控制台是否输出此消息
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        System.out.println("doFilter is called");
        // 1. 检查是否在白名单中
        String requestURI = httpRequest.getRequestURI();
        if (isInWhiteList(httpRequest)) {
            chain.doFilter(request, response);
            return;
        }

        // 获取Authorization头
        String authHeader = httpRequest.getHeader("Authorization");
        //没有提供token
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("Missing or invalid Authorization header");
            return;
        }

        // 提取Token
        String token = authHeader.substring(7);

        try {
            // 验证Token
            String username = JwtUtils.getUsernameFromToken(token);
            // 可以将用户名存入request，供后续Servlet使用
            httpRequest.setAttribute("username", username);
            chain.doFilter(request, response);
        } catch (Exception e) {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("Invalid token: " + e.getMessage());
        }
    }

    private boolean isInWhiteList(HttpServletRequest request) {
        // 获取上下文路径（如：/UserMgr_war_exploded）
        String contextPath = request.getContextPath();
        // 获取去上下文路径的URI（如：/login）
        String path = request.getRequestURI().substring(contextPath.length());

        return WHITE_LIST.stream().anyMatch(path::startsWith);
    }
}
